package com.ftw.commons

import android.annotation.SuppressLint
import android.app.Activity
import androidx.appcompat.view.menu.MenuPopupHelper
import androidx.appcompat.widget.PopupMenu
import android.view.ContextThemeWrapper
import android.view.View

/**
 * @Description:
 * @Author: fangtianwen
 * @Date: 2020/1/16 15:13
 */
abstract class IPopMenu {


    abstract fun getMenuId(): Int

    abstract fun onMenuItemClickListener(viewId: Int)

    abstract fun getGravity(): Int

    abstract fun margin(): Pair<Int, Int>


    fun create(view: View, activity: Activity) {

        val wrapper = ContextThemeWrapper(activity, R.style.popmenustyle)
        val popupMenu = PopupMenu(wrapper, view)
        popupMenu.menuInflater.inflate(getMenuId(), popupMenu.menu)
        popupMenu
            .setOnMenuItemClickListener {
                onMenuItemClickListener(it.itemId)
                return@setOnMenuItemClickListener false
            }

        popupMenu.gravity = getGravity()
        setForceShowIcon(popupMenu)
        popupMenu.show()
    }


    @SuppressLint("RestrictedApi")
    private fun setForceShowIcon(popupMenu: PopupMenu) {
        try {
            val fields = popupMenu.javaClass.declaredFields
            for (field in fields) {
                if ("mPopup" == field.name) {
                    field.isAccessible = true
                    val menuPopupHelper = field.get(popupMenu)
                    val classPopupHelper = Class.forName(menuPopupHelper.javaClass.name)
                    val setForceIcons = classPopupHelper.getMethod(
                        "setForceShowIcon", Boolean::class.javaPrimitiveType
                    )
                    setForceIcons.invoke(menuPopupHelper, true)
                    break
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }

    }


}